package com.sebiotec.login.ui.activity;

import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.lifecycle.ViewModelProviders;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.allen.library.RxHttpUtils;
import com.allen.library.manage.RxHttpManager;
import com.sebiotec.basecommon.utils.base.BaseActivity;
import com.sebiotec.basecommon.utils.constant.SjmConstant;
import com.sebiotec.basecommon.utils.tools.ActivityTool;
import com.sebiotec.basecommon.utils.tools.GsonUtil;
import com.sebiotec.basecommon.utils.tools.MobileTool;
import com.sebiotec.basecommon.utils.tools.SPUtils;
import com.sebiotec.basecommon.utils.tools.ToastTool;
import com.sebiotec.login.R;
import com.sebiotec.login.R2;
import com.sebiotec.login.model.get.ResponseLogin;
import com.sebiotec.login.model.get.UpdateApp;
import com.sebiotec.login.viewmodel.LoginViewModel;
import com.xuexiang.xui.widget.button.roundbutton.RoundButton;
import com.xuexiang.xui.widget.toast.XToast;
import com.xw.repo.XEditText;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import constacne.UiType;
import listener.UpdateDownloadListener;
import model.UiConfig;
import model.UpdateConfig;
import update.UpdateAppUtils;

/**
 * desc: 登录界面
 * author:mid
 * addtime:2020-02-07 09:32
 */
@Route(path = "/login/LoginActivity")
public class LoginActivity extends BaseActivity {

    @BindView(R2.id.ed_name)
    XEditText edName;
    @BindView(R2.id.ed_pwd)
    XEditText edPwd;
    @BindView(R2.id.btn_login)
    RoundButton btnLogin;
    @BindView(R2.id.tv_forget_pwd)
    TextView tvForgetPwd;
    @BindView(R2.id.view)
    View view;
    @BindView(R2.id.view2)
    View view2;
    @BindView(R2.id.tv_version)
    TextView tvVersion;
    @BindView(R2.id.iv_btn)
    ImageView ivBtn;
    private LoginViewModel mLoginViewModel;
    private String updateTitle = "发现新版本V2.0.0";
    private String updateContent = "1、Kotlin重构版\n2、支持自定义UI\n3、增加md5校验\n4、更多功能等你探索";
    private String fileName;
    private String versionName;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initUI() {
        versionName = MobileTool.getVersionName(this);
        tvVersion.setText("Ver." + versionName);

        fileName = SjmConstant.DownDIR + "/" + getPackageName();
        UpdateAppUtils.getInstance().deleteInstalledApk();
        SPUtils.put(SjmConstant.ISHOW, true);
        mLoginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);


        if (!TextUtils.isEmpty(SPUtils.get(SjmConstant.TOKEN, ""))) {
            if (1 == SPUtils.get(SjmConstant.ROLEID, 0)) {

                ARouter.getInstance().build("/App/MainActivity").navigation();
                ActivityTool.getInstance().popOneActivity(LoginActivity.this);
                return;
            } else if (3 == SPUtils.get(SjmConstant.ROLEID, 0)) {
                ARouter.getInstance().build("/App/JobMainActivity").navigation();
                ActivityTool.getInstance().popOneActivity(LoginActivity.this);
                return;
            } else if (5 == SPUtils.get(SjmConstant.ROLEID, 0)) {
                ARouter.getInstance().build("/App/ManagerMainActivity").navigation();
                ActivityTool.getInstance().popOneActivity(LoginActivity.this);
                return;
            }


        } else {
            String name = SPUtils.get(SjmConstant.LOGINID, "");
            edName.setTextEx(name);

            Log.d("versionName", versionName);
            mLoginViewModel.Update(versionName, new LoginViewModel.MyLoginDataCallBack() {
                @Override
                public void onDataSuccessCallBack(Object o) {
                    UpdateApp bean = (UpdateApp) o;
                    if (!TextUtils.isEmpty(bean.getFileName())) {
                        if (bean.getFileName().contains("f")) {
                            //强制更新
                            UpdateIsNoForce(SjmConstant.BASE_URL + bean.getUpgradePath(), true);
                        } else {
                            //非强制更新
                            UpdateIsNoForce(SjmConstant.BASE_URL + bean.getUpgradePath(), false);
                        }
                    }


                }

                @Override
                public void onDataFailCallBack(Object o,Object o1) {

                }
            });

        }
    }


    private void UpdateIsNoForce(String url, boolean isForce) {
        UpdateConfig updateConfig = new UpdateConfig();
        updateConfig.setCheckWifi(false);
        updateConfig.setAlwaysShowDownLoadDialog(true);
        updateConfig.setNeedCheckMd5(false);
        updateConfig.setNotifyImgRes(R.mipmap.ic_launcher);
        updateConfig.setForce(isForce);
        updateConfig.setApkSavePath(fileName);
        updateConfig.setShowDownloadingToast(false);
        UiConfig uiConfig = new UiConfig();
        uiConfig.setUiType(UiType.PLENTIFUL);

        UpdateAppUtils
                .getInstance()
                .apkUrl(url)

                .updateTitle("SJM")
                .updateContent(updateContent)
                .uiConfig(uiConfig)
                .updateConfig(updateConfig)

                .setUpdateDownloadListener(new UpdateDownloadListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onDownload(int progress) {

                    }

                    @Override
                    public void onFinish() {

                    }

                    @Override
                    public void onError(@NotNull Throwable e) {

                    }
                })
                .update();
    }


    @Override
    protected void initData() {


    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
         RxHttpUtils.cancel(SjmConstant.LOGINNET);

    }
    @Override
    protected void setListener() {
        edName.setOnXFocusChangeListener(new XEditText.OnXFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    view.setBackgroundColor(getResources().getColor(R.color.smj));
                } else {
                    view.setBackgroundColor(getResources().getColor(R.color.content_line));
                }
            }
        });
        edPwd.setOnXFocusChangeListener(new XEditText.OnXFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    view2.setBackgroundColor(getResources().getColor(R.color.smj));
                } else {
                    view2.setBackgroundColor(getResources().getColor(R.color.content_line));
                }
            }
        });

    }


    @OnClick({R2.id.btn_login, R2.id.tv_forget_pwd,R2.id.iv_btn})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.btn_login) {
            //else if (!CheckPwd.checkPasswordRule(edPwd.getTextEx().toString().trim())){
            //              XToast.error(LoginActivity.this,this.getString(R.string.yz_login_pwd)).show();
            //          }
            if (TextUtils.isEmpty(edName.getTextEx().toString().trim()) || TextUtils.isEmpty(edPwd.getTextEx().toString().trim())) {
                ToastTool.showError(LoginActivity.this, this.getString(R.string.yz_login_name));
//              XToast.error(LoginActivity.this,this.getString(R.string.yz_login_name)).show();
            } else {
                //password des 加密
                mLoginViewModel.login(edName.getTextEx().toString().trim(), edPwd.getTextEx().toString().trim(), new LoginViewModel.MyLoginDataCallBack() {
                    @Override
                    public void onDataSuccessCallBack(Object o) {
                        ResponseLogin responseLogin = (ResponseLogin) o;


                        if (responseLogin.getIsResetPwd()==1){
                            SPUtils.put(SjmConstant.LOGINID, edName.getTextEx().toString().trim());
                            XToast.error(LoginActivity.this,getString(R.string.account_return)).show();
                            Bundle bundle = new Bundle();        //得到bundle对象
                            bundle.putString("Token", responseLogin.getToken());
                            //   map.put("LoginId", SPUtils.get(SjmConstant.LOGINID,""));
                            //        map.put("Token",)

                            if (1 == responseLogin.getRoleId()) {
                                ARouter.getInstance().build("/book/UpdatePwdActivity").withBundle("login", bundle).navigation();
                                ActivityTool.getInstance().popOneActivity(LoginActivity.this);
                            } else if (3 == responseLogin.getRoleId()) {
                                ARouter.getInstance().build("/driver/UpdatePwdActivity").withBundle("login", bundle).navigation();
                                ActivityTool.getInstance().popOneActivity(LoginActivity.this);
                            } else if (5 == responseLogin.getRoleId()) {
                                ARouter.getInstance().build("/manager/UpdatePwdActivity").withBundle("login", bundle).navigation();
                                ActivityTool.getInstance().popOneActivity(LoginActivity.this);
                            }
                        }else{
                            SPUtils.put(SjmConstant.LOGINID, edName.getTextEx().toString().trim());
                            SPUtils.put(SjmConstant.TOKEN, responseLogin.getToken());
                            SPUtils.put(SjmConstant.ROLEID, responseLogin.getRoleId());
                            SPUtils.put(SjmConstant.SINTERVALMINS, responseLogin.getSIntervalMins());

                            if (1 == responseLogin.getRoleId()) {
                                ARouter.getInstance().build("/App/MainActivity").navigation();
                                ActivityTool.getInstance().popOneActivity(LoginActivity.this);
                            } else if (3 == responseLogin.getRoleId()) {
                                ARouter.getInstance().build("/App/JobMainActivity").navigation();
                                ActivityTool.getInstance().popOneActivity(LoginActivity.this);
                            } else if (5 == responseLogin.getRoleId()) {
                                ARouter.getInstance().build("/App/ManagerMainActivity").navigation();
                                ActivityTool.getInstance().popOneActivity(LoginActivity.this);

                            }
                        }



                    }

                    @Override
                    public void onDataFailCallBack(Object o,Object o1) {
                        String s=(String)o;
                        if ("300".equals(s)){
                            XToast.error(LoginActivity.this,getString(R.string.loginId_or_password_error)).show();
                        }else if ("301".equals(s)){
                            XToast.error(LoginActivity.this,getString(R.string.loginId_or_password_error)).show();
                        }else if ("302".equals(s)){
                            XToast.error(LoginActivity.this,getString(R.string.account_done)).show();
                        }else if ("303".equals(s)){
                            XToast.error(LoginActivity.this,getString(R.string.account_change)).show();
                            if (o1!=null){
                                String s1=(String)o1;
                                Bundle bundle = new Bundle();        //得到bundle对象

                                //   map.put("LoginId", SPUtils.get(SjmConstant.LOGINID,""));
                                //        map.put("Token",
                                ResponseLogin responseLogin = GsonUtil.getGson().fromJson(s1, ResponseLogin.class);
                                SPUtils.put(SjmConstant.LOGINID, edName.getTextEx().toString().trim());
                                bundle.putString("Token", responseLogin.getToken());
                                if (1 == responseLogin.getRoleId()) {
                                    ARouter.getInstance().build("/book/UpdatePwdActivity").withBundle("login", bundle).navigation();
                                    ActivityTool.getInstance().popOneActivity(LoginActivity.this);
                                } else if (3 == responseLogin.getRoleId()) {
                                    ARouter.getInstance().build("/driver/UpdatePwdActivity").withBundle("login", bundle).navigation();
                                    ActivityTool.getInstance().popOneActivity(LoginActivity.this);
                                } else if (5 == responseLogin.getRoleId()) {
                                    ARouter.getInstance().build("/manager/UpdatePwdActivity").withBundle("login", bundle).navigation();
                                    ActivityTool.getInstance().popOneActivity(LoginActivity.this);
                                }

                            }

                        }else if ("304".equals(s)){
                            XToast.error(LoginActivity.this,getString(R.string.account_sync)).show();
                        }else if ("306".equals(s)){
                            XToast.error(LoginActivity.this, R.string.loign_id_is_done).show();
                        }else{
                            XToast.error(LoginActivity.this,getString(R.string.login_failed)).show();
                        }

                    }
                });

//              //golgon
//              ARouter.getInstance().build("/App/MainActivity").navigation();
            }
//            //测试
//            if (TextUtils.isEmpty(edName.getTextEx().toString().trim())) {
//                XToast.error(LoginActivity.this, this.getString(R.string.yz_login_name)).show();
//            } else if (TextUtils.isEmpty(edPwd.getTextEx().toString().trim())) {
//                XToast.error(LoginActivity.this, this.getString(R.string.yz_login_pwd)).show();
//            } else {
//                //golgon
//
//
//            }


        } else if (id == R.id.tv_forget_pwd) {
        }else if (id==R.id.iv_btn){
             SettingDialogFragment.newInstance("").show(getSupportFragmentManager(),"1");
        }
    }




}
